# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')

import threading,string
import time 
from time import sleep
import os
import logging
import json
import pika
from task import *
from base_thread import *
#提交任务到FastCGI
class RPCThread(Thread):  
	def __init__(self,client,rpc_server,service_center):  
		Thread.__init__(self) 
		self.client = client
		self.rpc_server = rpc_server
		self.service_center = service_center
	
	def on_run(self):
		logging.info("RpcThread Begin")
		try:
			self.rpc_server.listen(self.request)
		except Exception as e:
			logging.error('RpcThread.on_run')
			logging.exception(e)
			time.sleep(0.1)
		logging.info("RpcThread End")	


	def on_stop(self):
		logging.info('RpcThread on stop')
		self.rpc_server.stop()
		
	def request(self, ch, method, props, body):  #回调
		logging.info("收到RPC调用")#,body.decode()
		if body:
			req_str=body.decode()
			if req_str.startswith("{") and req_str.endswith("}"):
				try:
					#logging.info('get a rpc')
					data= self.process_rpc(req_str,ch, props)
					logging.debug(data)
				except Exception as e:
					logging.error('RpcThread.request')
					logging.exception(e)
			else:
				try:
					#logging.info('get a message')
					ret=self.client.send(req_str)
					logging.info(ret)
				except Exception as e:
					logging.error('RpcThread.RPC')
					logging.exception(e)
				
	
	def process_rpc(self,body,ch,props):
		response=''
		task = Task.createFromJson(body)
		if task.checkSign() and task.checkTimes():
			if task.plan == 'rpc':#循环任务
				#通过FastCGI协议发送给php-fpm执行
				logging.info(props.reply_to)
				if self.service_center.check(task):
					response = self.service_center.execute(task)
				else:
					response=self.client.send(task.toJson(),task.command)
				ch.basic_publish(exchange='',
                     routing_key=props.reply_to,  # props.reply_to从客户端取出双方约定好存放返回结果的queue
                     properties=pika.BasicProperties(correlation_id=props.correlation_id),  # props.correlation_id 从客户端取出当前请求的ID返回给客户端做验证
                     body=str(response))	
		return response

